package com.sca.order.controller;

import com.sca.order.annotation.RequireToken;
import com.sca.order.entity.api.BaseResult;
import com.sca.order.entity.enums.ResultEnum;
import com.sca.order.service.SeckillService;
import com.sca.order.service.StockService;
import com.sca.order.utils.GoodBloomFilter;
import com.sca.order.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author liuxianfei
 * @since 2020/11/3 12:27
 */
@Api
@RestController
@RequestMapping("/order/v1/seckill")
public class SeckillController {

    private final SeckillService seckillService;
    private final StockService stockService;

    public SeckillController(SeckillService seckillService, StockService stockService) {
        this.seckillService = seckillService;
        this.stockService = stockService;
    }

    @GetMapping("/{goodId}")
    @ApiOperation("秒杀")
    public BaseResult<?> seckill(@RequestHeader("userId") Integer userId, @PathVariable Long goodId) {
        if (userId == null) {
            return new BaseResult<>(ResultEnum.ERR_PARAM);
        }
        // 布隆过滤器校验goodId
        if (!GoodBloomFilter.mightContain(goodId)) {
            return new BaseResult<>(ResultEnum.ERR_PARAM);
        }
        if (seckillService.seckill(userId, goodId)) {
            return new BaseResult<>();
        }
        return new BaseResult<>(ResultEnum.ERR_SECKILL);
    }

    @GetMapping("/forRedis/{goodId}")
    @ApiOperation("秒杀2")
    @RequireToken
    @ApiImplicitParam(name = JwtUtil.HEADER_AUTHORIZATION, value = "token", paramType = "header", required = true)
    public BaseResult<?> seckillForRedis(@ApiIgnore @RequestHeader(JwtUtil.USER_ID) Integer userId, @PathVariable Long goodId) {
        if (userId == null) {
            return new BaseResult<>(ResultEnum.ERR_PARAM);
        }
        // 布隆过滤器校验goodId
        if (!GoodBloomFilter.mightContain(goodId)) {
            return new BaseResult<>(ResultEnum.ERR_PARAM);
        }
        if (seckillService.seckillForRedis(userId, goodId)) {
            return new BaseResult<>();
        }
        return new BaseResult<>(ResultEnum.ERR_SECKILL);
    }

    @GetMapping("/addStock/{goodId}")
    @ApiOperation("增加库存")
    public BaseResult<?> addStock(@PathVariable Long goodId, Integer type) {
        if (!GoodBloomFilter.mightContain(goodId)) {
            return new BaseResult<>(ResultEnum.ERR_PARAM);
        }
        if (stockService.addStock(goodId, 1, type)) {
            return new BaseResult<>();
        }
        return new BaseResult<>(ResultEnum.ERR);
    }

}
